<template>
  <div>
    <!-- 按钮 -->
    <el-button style="margin:10px 10px" type="primary" icon="el-icon-refresh-right" circle
      @click="getPageAccountDetailList"></el-button>
    <!-- 表格
      data 展示数据 —— 数组类型
    -->
    <el-button @click="handleExport2" style="margin-right: 30px;">导出报表</el-button>
    <el-date-picker v-model="valueData" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels
      range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
    </el-date-picker>
    <el-button style="margin-left: 10px;" icon="el-icon-search" @click="rangeChange"></el-button>
    <el-table :height="tableHeight" ref="tableData" id="table" :summary-method="getSummaries" show-summary
      style="width: 100%;" border :data="list">
      <!-- 发起人 -->
      <el-table-column prop="fromUserNickName" label="发起人昵称" align="center">
      </el-table-column>
      <el-table-column prop="dayCostGold" label="核销金币" align="center">
      </el-table-column>
      <el-table-column prop="dayCostMoney" label="核销金额" align="center">
      </el-table-column>
      <el-table-column prop="dayMessageCostMoney" label="聊天金额" align="center">
      </el-table-column>
      <el-table-column prop="dayAudioCostMoney" label="语音聊天金额" align="center">
      </el-table-column>
      <el-table-column prop="dayVideoCostMoney" label="视频聊天金额" align="center">
      </el-table-column>
      <el-table-column prop="dayGiftCostMoney" label="打赏金额" align="center">
      </el-table-column>
      <!--受益方 -->
      <el-table-column prop="toUserNickName" label="受益人昵称" align="center">
      </el-table-column>
      <el-table-column prop="messageNum" label="聊天条数" align="center">
      </el-table-column>
      <el-table-column prop="messageCostGold" label="聊天消耗金币" align="center">
      </el-table-column>
      <el-table-column prop="audioDuration" label="语音分钟数" align="center">
      </el-table-column>
      <el-table-column prop="audioCostGold" label="语音消耗金币" align="center">
      </el-table-column>
      <el-table-column prop="videoDuration" label="视频分钟数" align="center">
      </el-table-column>
      <el-table-column prop="videoCostGold" label="视频消耗金币" align="center">
      </el-table-column>
      <el-table-column prop="giftCostGold" label="礼物打赏金币" align="center">
      </el-table-column>

      <!-- 抽成 -->
      <el-table-column prop="messageReward" label="聊天抽成" align="center">
      </el-table-column>
      <el-table-column prop="audioReward" label="语音聊天抽成" align="center">
      </el-table-column>
      <el-table-column prop="videoReward" label="视频聊天抽成" align="center">
      </el-table-column>
      <el-table-column prop="giftReward" label="礼物打赏抽成" align="center">
      </el-table-column>
      <el-table-column prop="totalReward" label="用户抽成合计" align="center">
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <el-pagination style="margin-top:20px;textAlign:center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination> -->
  </div>
</template>

<script>
  import {
    exportToExcel
  } from '@/utils/Export2Excel'
  export default {
    name: 'goldCostTable',
    data() {
      return {
        tableHeight:800,
        valueData: [],
        //页码
        pageNumber: 1,
        //每页数量
        pageSize: 10,
        //总条数
        total: 0,
        //列表数据
        list: [],
      }
    },
    created() {
      this.tableHeight = window.innerHeight - 120
    },
    updated() {
      this.$nextTick(() => {
        this.$refs.tableData.doLayout();
      });
    },
    mounted() {
      // 设置表格高度
      this.tableHeight = window.innerHeight - 120
      // / 监听浏览器窗口变化，动态计算表格高度，
      window.onresize = () => {
        return (() => {
          this.tableHeight = window.innerHeight - 120
        })()
      }



      // 获取当前时间
      const today = new Date();
      // 获取当前时间(today)的年份
      const year = today.getFullYear();
      // 获取月份
      const month = String(today.getMonth() + 1).padStart(2, '0');
      // // 获取当前日
      // const day = String(today.getDate()).padStart(2, '0');
      // // 得到年月日
      // const thisDayDate = `${year}-${month}-${day}`; //打印当前日期
      console.log(year, month)
      let ym = year + '-' + month
      this.valueData[0] = ym + '-' + '01'
      this.valueData[1] = ym + '-' + this.getLastDayOfMonth(year, month)
      console.log(this.valueData)
      this.getPageAccountDetailList()
    },
    methods: {
      // 获取某年某月的最后一天
      getLastDayOfMonth(year, month) {
        var date = new Date(year, month - 1, '01');
        //设置日期
        date.setDate(1);
        //设置月份
        date.setMonth(date.getMonth() + 1);
        //获取本月的最后一天
        var cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
        //返回结果
        return cdate.getDate();
      },
      round(num, iCount = 2) {
        // iCount 保留几位小数
        let changeNum = num
        let zs = true
        // 判断是否是负数
        if (changeNum < 0) {
          changeNum = Math.abs(changeNum)
          zs = false
        }
        const iB = Math.pow(10, iCount)
        // 有时乘100结果也不精确
        const value1 = changeNum * iB
        let intDecSet = []
        let intDecHun = []

        let fValue = value1
        const value2 = value1.toString()
        const iDot = value2.indexOf('.')

        // 如果是小数
        if (iDot !== -1) {
          intDecSet = changeNum.toString().split('.')

          // 如果是科学计数法结果
          if (intDecSet[1].indexOf('e') !== -1) {
            return Math.round(value1) / iB
          }
          intDecHun = value2.split('.')

          if (intDecSet[1].length <= iCount) {
            return parseFloat(num, 10)
          }

          const fValue3 = parseInt(intDecSet[1].substring(iCount, iCount + 1), 10)

          if (fValue3 >= 5) {
            fValue = parseInt(intDecHun[0], 10) + 1
          } else {
            // 对于传入的形如111.834999999998 的处理（传入的计算结果就是错误的，应为111.835）
            if (fValue3 === 4 && intDecSet[1].length > 10 && parseInt(intDecSet[1].substring(iCount + 1, iCount + 2),
                10) === 9) {
              fValue = parseInt(intDecHun[0], 10) + 1
            } else {
              fValue = parseInt(intDecHun[0], 10)
            }
          }
        }
        // 如果是负数就用0减四舍五入的绝对值
        let val = zs ? (fValue / iB) : (0 - fValue / iB)

        const d = val.toString().split('.')
        if (d.length === 1) {
          return val.toString() + '.00'
        }
        if (d.length > 1) {
          if (d[1].length < 2) {
            val = val.toString() + '0'
          }
          return val
        }
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index === 7 || index === 8 || index === 10 || index === 12) {
            sums[index] = '';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
            sums[index] = this.round(sums[index])
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      checkMonth(dt1, dt2) {
        dt1 = new Date(dt1.replace(/-/g, "/"));
        dt2 = new Date(dt2.replace(/-/g, "/"));
        if (dt1.getFullYear() == dt2.getFullYear() && dt1.getMonth() == dt2.getMonth()) {
          console.log('同')
          return 1
        } else {
          console.log('不同')
          return 0
        }
      },
      rangeChange() {
        console.log('时间范围', this.valueData)
        // console.log(this.tableData)
        // this.tableData[0].sDate = this.valueData[0]
        // this.tableData[0].eDate = this.valueData[1]
        // console.log(this.tableData)
        if (!this.valueData) {
          this.valueData = []
        }
        if (this.checkMonth(this.valueData[0], this.valueData[1]) == 1) {
          this.getPageAccountDetailList()
        } else {
          this.$message({
            message: '日期选择只能同一个月内',
            type: 'error',
            duration: 5 * 1000
          })
        }


      },
      handleExport2() {
        let auditResult = prompt('报表名字：');
        if (auditResult != null && auditResult != "") {
          exportToExcel('#table', auditResult);
        }
      },
      addDate(strDate) {
        let dateFormat = new Date(strDate);
        dateFormat = dateFormat.setDate(dateFormat.getDate() + 1);
        dateFormat = new Date(dateFormat);
        let y = dateFormat.getFullYear()
        let m = (dateFormat.getMonth() + 1).toString().padStart(2, '0')
        let d = dateFormat.getDate().toString().padStart(2, '0')
        return `${y}-${m}-${d}`
      },
      async getPageAccountDetailList() {
        let res = await this.$API.running.goldCostTable({
          endTime: this.addDate(this.valueData[1]),
          startTime: this.valueData[0]
        })
        console.log('财务统计表-金币核销统计表', res)
        // this.total = res.data.sumLine;
        this.list = res.data;
      },
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.pageSize = val
      },
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pageNumber = val
      },
      // filterTag(value, row) {
      //   console.log(value, row)
      //   return row.operateType == value;
      // },
    }
  }
</script>

<style scoped>
  .el-table {
    overflow: visible !important;
  }
</style>
